package factory.one.service;

import factory.one.entity.Refund;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.List;

/**
 * @author sk.z
 * 2023/8/22
 * 退货
 **/
@Service
public class RefundService {

    private final Logger log = LoggerFactory.getLogger(RefundService.class);

    private final JdbcTemplate jdbcTemplate;

    public RefundService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public Long add(Refund refund) {
        PreparedStatementCreator preparedStatementCreator = con -> {
            PreparedStatement statement = con.prepareStatement("insert into REFUND(order_id,batch_id,number,create_user,create_time) values(?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
            statement.setLong(1, refund.getOrderId());
            statement.setLong(2, refund.getBatchId());
            statement.setInt(3, refund.getNumber());
            statement.setString(4, refund.getCreateUser());
            statement.setTimestamp(5, new Timestamp(refund.getCreateTime().getTime()));
            return statement;
        };
        GeneratedKeyHolder holder = new GeneratedKeyHolder();
        jdbcTemplate.update(preparedStatementCreator, holder);
        return holder.getKey() == null ? null : holder.getKey().longValue();
    }

    public List<Refund> listByOrder(Long orderId) {
        return jdbcTemplate.query("select * from REFUND where order_id = ? order by id desc ", new RefundRowMapper(), orderId);
    }

    private static class RefundRowMapper implements RowMapper<Refund> {
        @Override
        public Refund mapRow(ResultSet rs, int rowNum) throws SQLException {
            Refund refund = new Refund();
            refund.setId(rs.getLong("id"));
            refund.setOrderId(rs.getLong("order_id"));
            refund.setBatchId(rs.getLong("batch_id"));
            refund.setNumber(rs.getInt("number"));
            refund.setCreateUser(rs.getString("create_user"));
            refund.setCreateTime(rs.getTimestamp("create_time"));
            return refund;
        }
    }

}
